﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using QXBook.Model;
using System.Data.Common;
using System.Data.SqlClient;
using System.Data;
using QXBook.Utils;
using System.Configuration;
using System.Web;

namespace QXBook.Service
{
    public class UsersService : ServiceBase
    {
        /// <summary>
        /// 注册用户
        /// </summary>
        /// <param name="tmpuser"></param>
        /// <returns></returns>
        public string Register(UsersInfo tmpuser)
        {
            UsersInfo userinfo = this.CheckUser(tmpuser.UserName, string.Empty);

            if (userinfo != null)
            {
                return MsgConst.USER_FIND;
            }

            string result = this.AddUser(tmpuser);
            if (string.IsNullOrEmpty(result))
            {
                userinfo = this.CheckUser(tmpuser.UserName, string.Empty);
                object Tempuser = SessionState.Get(ConfigurationManager.AppSettings["UserSessionName"]);
                if (Tempuser == null)
                {
                    SessionState.Set(ConfigurationManager.AppSettings["UserSessionName"], userinfo.UserName);
                }
                else
                {
                    SessionState.Remove(ConfigurationManager.AppSettings["UserSessionName"]);
                    SessionState.Set(ConfigurationManager.AppSettings["UserSessionName"], userinfo.UserName);
                }
                return MsgConst.OK;
            }
            return string.Empty;
        }

        public string UserLogin(string username, string password)
        {
            UsersInfo userinfo = this.CheckUser(username, password);

            //用户密码错误
            if (userinfo == null)
            {
                return MsgConst.USER_USERORPWDERROR;
            }

            //用户已经被锁定
            if (userinfo.IsLock == YesNo.Yes)
            {
                return MsgConst.USER_ISLOCK;
            }

            object Tempuser = SessionState.Get(ConfigurationManager.AppSettings["UserSessionName"]);
            if (Tempuser == null)
            {
                SessionState.Set(ConfigurationManager.AppSettings["UserSessionName"], userinfo.UserName);
            }

            ServiceFactory.CreateInstance<ShoppingCartService>().UpdateShoppingCart(userinfo.UserID);
            return MsgConst.OK;
        }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="userName"></param>
        /// <param name="password"></param>
        /// <returns></returns>
        private UsersInfo CheckUser(string userName, string password)
        {
            string sql = @"SELECT A.UserID,A.UserName,A.NickName,A.LevelID,B.LevelName,A.IsLock,A.Money,A.AddDate 
            FROM Users A LEFT JOIN Level B ON B.LevelID=A.LevelID WHERE 1=1";
            if (!string.IsNullOrEmpty(userName))
            {
                sql += " AND UserName=@UserName";
            }
            if (!string.IsNullOrEmpty(password))
            {
                sql += " AND PassWord=@PassWord";
            }

            DbCommand cmd = new SqlCommand(sql);
            base.db.AddInParameter(cmd, "@UserName", DbType.String, userName);
            base.db.AddInParameter(cmd, "@PassWord", DbType.String, password);
            DataSet ds = this.db.ExecuteDataSet(cmd);

            if (ds != null && ds.Tables.Count > 0 && ds.Tables[0].Rows.Count > 0)
            {
                UsersInfo user = new UsersInfo();
                foreach (DataRow dr in ds.Tables[0].Rows)
                {
                    user.UserID = CommonUtils.ToInt(dr["UserID"]);
                    user.UserName = CommonUtils.ToString(dr["UserName"]);
                    user.NickName = CommonUtils.ToString(dr["NickName"]);
                    user.LevelID = CommonUtils.ToInt(dr["LevelID"]);
                    user.LevelName = CommonUtils.ToString(dr["LevelName"]);
                    user.IsLock = (YesNo)CommonUtils.ToInt(dr["IsLock"]);
                    user.Money = CommonUtils.ToDecimal(dr["Money"]);
                    user.AddDate = CommonUtils.ToTime(dr["AddDate"].ToString());
                }

                return user;
            }
            return null;
        }

        /// <summary>
        /// 验证邮箱
        /// </summary>
        /// <param name="email"></param>
        /// <returns></returns>
        private UsersInfo CheckUserEmail(string email)
        {
            string sql = @"SELECT SELECT A.UserID,A.UserName,A.NickName,A.LevelID,B.LevelName,A.IsLock,A.Money,A.AddDate 
            FROM Users A JOIN Level B ON B.LevelID=A.LevelID WHERE Email=@Email";

            DbCommand cmd = new SqlCommand(sql);
            base.db.AddInParameter(cmd, "@Email", DbType.String, email);
            DataSet ds = this.db.ExecuteDataSet(cmd);

            if (ds != null && ds.Tables.Count > 0 && ds.Tables[0].Rows.Count > 0)
            {
                UsersInfo user = new UsersInfo();
                foreach (DataRow dr in ds.Tables[0].Rows)
                {
                    user.UserID = CommonUtils.ToInt(dr["UserID"]);
                    user.UserName = CommonUtils.ToString(dr["UserName"]);
                    user.NickName = CommonUtils.ToString(dr["NickName"]);
                    user.LevelID = CommonUtils.ToInt(dr["LevelID"]);
                    user.LevelName = CommonUtils.ToString(dr["LevelName"]);
                    user.IsLock = (YesNo)CommonUtils.ToInt(dr["IsLock"]);
                    user.Money = CommonUtils.ToDecimal(dr["Money"]);
                    user.AddDate = CommonUtils.ToTime(dr["AddDate"].ToString());
                }

                return user;
            }
            return null;
        }

        public UsersInfo GetUsersInfo()
        {
            this.UserInit();
            return this._user;
        }

        private void UserInit()
        {
            if (this._user != null) return;
            object TempUser = null;
            if (string.IsNullOrEmpty(this._name))
            {
                this._name = CommonUtils.ToString(SessionState.Get(ConfigurationManager.AppSettings["UserSessionName"]));
            }

            if (!string.IsNullOrEmpty(this._name))
            {
                this._user = this.GetUsersInfo(this._name);
            }

            TempUser = SessionState.Get(ConfigurationManager.AppSettings["UserSessionName"]);
            if (TempUser == null)
            {
                if (this._user != null && this._user.IsLock == YesNo.No)
                {
                    SessionState.Set(ConfigurationManager.AppSettings["UserSessionName"], this._user.UserName);
                }
                else
                {
                    SessionState.Remove(ConfigurationManager.AppSettings["UserSessionName"]);
                }
            }
        }

        /// <summary>
        /// 检测管理员登录
        /// </summary>
        public void CheckUserLogin()
        {
            this.UserInit();

            if (this._user == null)
            {
                HttpContext.Current.Response.Redirect("/Login.aspx");
            }
        }

        public UsersInfo GetUsersInfo(int userID)
        {
            return this.GetUsersInfo(userID, string.Empty);
        }

        public UsersInfo GetUsersInfo(string userName)
        {
            return this.GetUsersInfo(0, userName);
        }

        private UsersInfo GetUsersInfo(int userID, string userName)
        {
            string sql = @"SELECT A.UserID,A.UserName,A.NickName,A.RealName,A.CardCode,A.Address,A.QQ,A.MSN,A.Telphone,A.Email,A.LevelID,B.LevelName,A.IsLock,A.Money,A.AddDate 
            FROM Users A LEFT JOIN Level B ON B.LevelID=A.LevelID WHERE 1=1";

            if (userID > 0)
            {
                sql += " AND A.UserID=" + userID;
            }

            if (!string.IsNullOrEmpty(userName))
            {
                sql += " AND A.UserName='" + userName + "'";
            }

            DataSet ds = this.db.ExecuteDataSet(CommandType.Text, sql);

            if (ds != null && ds.Tables.Count > 0 && ds.Tables[0].Rows.Count > 0)
            {
                UsersInfo user = new UsersInfo();
                foreach (DataRow dr in ds.Tables[0].Rows)
                {
                    user.UserID = CommonUtils.ToInt(dr["UserID"]);
                    user.UserName = CommonUtils.ToString(dr["UserName"]);
                    user.NickName = CommonUtils.ToString(dr["NickName"]);
                    user.RealName = CommonUtils.ToString(dr["RealName"]);
                    user.CardCode = CommonUtils.ToString(dr["CardCode"]);
                    user.QQ = CommonUtils.ToString(dr["QQ"]);
                    user.MSN = CommonUtils.ToString(dr["MSN"]);
                    user.Telphone = CommonUtils.ToString(dr["Telphone"]);
                    user.Email = CommonUtils.ToString(dr["Email"]);
                    user.LevelID = CommonUtils.ToInt(dr["LevelID"]);
                    user.LevelName = CommonUtils.ToString(dr["LevelName"]);
                    user.IsLock = (YesNo)CommonUtils.ToInt(dr["IsLock"]);
                    user.Money = CommonUtils.ToDecimal(dr["Money"]);
                    user.AddDate = CommonUtils.ToTime(dr["AddDate"].ToString());
                }

                return user;
            }
            return null;
        }

        /// <summary>
        /// 添加用户
        /// </summary>
        /// <param name="user"></param>
        /// <returns></returns>
        public string AddUser(UsersInfo user)
        {
            DbCommand cmd = new SqlCommand();
            cmd.CommandText = @"INSERT INTO Users (UserName,PassWord,NickName,RealName,CardCode,QQ,MSN,Telphone,Email,LevelID,IsLock,AddDate)
                                VALUES(@UserName,@PassWord,@NickName,@RealName,@CardCode,@QQ,@MSN,@Telphone,@Email,0,0,GETDATE())";

            base.db.AddInParameter(cmd, "@UserName", DbType.String, user.UserName);
            base.db.AddInParameter(cmd, "@PassWord", DbType.String, user.PassWord);
            base.db.AddInParameter(cmd, "@NickName", DbType.String, user.NickName);
            base.db.AddInParameter(cmd, "@CardCode", DbType.String, user.CardCode);
            base.db.AddInParameter(cmd, "@RealName", DbType.String, user.RealName);
            base.db.AddInParameter(cmd, "@QQ", DbType.String, user.QQ);
            base.db.AddInParameter(cmd, "@MSN", DbType.String, user.MSN);
            base.db.AddInParameter(cmd, "@Telphone", DbType.String, user.Telphone);
            base.db.AddInParameter(cmd, "@Email", DbType.String, user.Email);
            base.db.ExecuteNonQuery(cmd);

            return string.Empty;
        }

        /// <summary>
        /// 修改密码
        /// </summary>
        /// <param name="user"></param>
        /// <returns></returns>
        public string UpdatePWD(UsersInfo user)
        {
            DbCommand cmd = new SqlCommand();
            cmd.CommandText = @"UPDATE Users SET PassWord=@PassWord,UpdateDate=GETDATE() WHERE UserID=@UserID";

            base.db.AddInParameter(cmd, "@PassWord", DbType.String, user.PassWord);
            base.db.AddInParameter(cmd, "@UserID", DbType.Int32, user.UserID);
            base.db.ExecuteNonQuery(cmd);

            return string.Empty;
        }

        /// <summary>
        /// 编辑帐号资料
        /// </summary>
        /// <param name="user"></param>
        /// <returns></returns>
        public string UpdateUserInfo(UsersInfo user)
        {
            DbCommand cmd = new SqlCommand();
            cmd.CommandText = @"UPDATE Users SET RealName=@RealName,CardCode=@CardCode,QQ=@QQ,MSN=@MSN,Telphone=@Telphone,Email=@Email,UpdateDate=GETDATE() WHERE UserID=@UserID";

            base.db.AddInParameter(cmd, "@PassWord", DbType.String, user.PassWord);
            base.db.AddInParameter(cmd, "@UserID", DbType.Int32, user.UserID);
            base.db.ExecuteNonQuery(cmd);

            return string.Empty;
        }

        /// <summary>
        /// 获取用户
        /// </summary>
        /// <param name="ps"></param>
        /// <param name="condition"></param>
        /// <returns></returns>
        public List<UsersInfo> GetModelList(ref PagerState ps, UsersCondition condition)
        {
            List<UsersInfo> list = new List<UsersInfo>();
            DbCommand cmd = new SqlCommand();

            StringBuilder sbSql = new StringBuilder();
            sbSql.Append("SELECT A.UserID,A.UserName,A.NickName,A.LevelID,B.LevelName,A.IsLock,A.Money,A.AddDate ");
            sbSql.Append(" FROM Users A LEFT JOIN Level B ON B.LevelID=A.LevelID ");
            sbSql.Append(" WHERE 1=1");
            if (condition != null)
            {
                if (condition.IsLock != YesNo.Unknow)
                {
                    sbSql.Append(" AND A.IsLock=" + (int)condition.IsLock);
                }
            }

            DataTable dt = this.GetListPager(ref ps, sbSql.ToString(), "UserID", cmd);

            if (dt != null && dt.Rows.Count > 0)
            {
                foreach (DataRow dr in dt.Rows)
                {
                    UsersInfo user = new UsersInfo();
                    user.UserID = CommonUtils.ToInt(dr["UserID"]);
                    user.UserName = CommonUtils.ToString(dr["UserName"]);
                    user.NickName = CommonUtils.ToString(dr["NickName"]);
                    user.LevelID = CommonUtils.ToInt(dr["LevelID"]);
                    user.LevelName = CommonUtils.ToString(dr["AddDate"]);
                    user.IsLock = (YesNo)CommonUtils.ToInt(dr["IsLock"]);
                    user.Money = CommonUtils.ToInt(dr["Money"].ToString());
                    user.AddDate = CommonUtils.ToTime(dr["AddDate"].ToString());
                    list.Add(user);
                }
            }

            return list;
        }

        private string _name = string.Empty;
        private UsersInfo _user = null;
    }
}
